﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoNyaa.Logic.Entities;
using System.Threading;
using System.Net;
using MonoTorrent.Common;
using MonoTorrent.Client;
using System.Collections.Concurrent;
using System.IO;

namespace AutoNyaa.Logic
{
    public class DownloadManager
    {
        public ConcurrentQueue<Download> Downloads { get; set; }

        private bool _exit = false;

        public void StartDownload(string url, string location)
        {
            Download download = new Download()
            {
                Url = url,
                Location = location,
                Downloaded = false
            };
            Downloads.Enqueue(download);
        }

        public DownloadManager()
        {
            Downloads = new ConcurrentQueue<Download>();

            if (!Directory.Exists(Properties.UserSettings.Default.TorrentFolder))
            {
                Directory.CreateDirectory(Properties.UserSettings.Default.TorrentFolder);
            }
        }


        public void Run()
        {
            while (!_exit)
            {
                Download download;

                while (Downloads.TryDequeue(out download))
                {
                    if (!download.Downloaded)
                    {
                        Console.WriteLine("Downloading " + download.Url);
                        download.Location += ".torrent";

                        WebClient webClient = new WebClient();

                        webClient.DownloadFile(new Uri(download.Url), download.Location);
                        download.Downloaded = true;

                        OnTorrentDownloadCompleted(download);
                    }
                }

                Thread.Sleep(1000);
            }
        }

        public delegate void TorrentDownloadCompletedHandler(Download download);

        public event TorrentDownloadCompletedHandler TorrentDownloadCompleted;

        protected void OnTorrentDownloadCompleted(Download download)
        {
            if (TorrentDownloadCompleted != null)
            {
                TorrentDownloadCompleted(download);
            }
        }

        public void Exit()
        {
            _exit = true;
        }
    }
}